package org.dreamwork.jasmine2.web.html;

import org.dreamwork.jasmine2.configure.JasmineConfig;
import org.dreamwork.jasmine2.engine.HttpContext;
import org.dreamwork.jasmine2.i18n.I18nUtil;
import org.dreamwork.jasmine2.web.IWebControl;
import org.dreamwork.jasmine2.web.controls.WebContainer;
import org.dreamwork.jasmine2.events.EventException;
import org.dreamwork.util.StringUtil;

import javax.servlet.ServletContext;
import java.io.PrintWriter;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: seth
 * Date: 2009-7-27
 * Time: 18:37:26
 */
public class TableCell extends WebContainer {
    public TableCell () {
        this (false);
    }

    public TableCell (boolean isHeader) {
        this.htmlTagName = isHeader ? "th" : "td";
        viewStateEnabled = false;
    }

    @Override
    public void onPrerender (IWebControl sender, HttpContext context) throws EventException {
        if (text == null) return;

        String result = text.toString ();
        if (!StringUtil.isEmpty (result)) {
            ServletContext application = context.getApplication ();
            if (application.getAttribute (JasmineConfig.JASMINE_I18N_HOLDER) != null)
                result = I18nUtil.eval (result, this);
            text = I18nUtil.escapeI18n (result);
        }
    }

    @Override
    public void render (PrintWriter writer) throws IOException, EventException {
        if (childControls.isEmpty ()) {
            super.beginTag (writer);
            if (text != null && text.length () > 0)
                writer.print (text);
            super.endTag (writer);
        } else
            super.render (writer);
    }
}